#include "chat.h"
#include "ui_chat.h"

#include <QDebug>
#include <QThread>
#include <QFileDialog>
#include <QMessageBox>
#include <QIODevice>

Chat::Chat(QString name_, QString _id, QString name, QString id_, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Chat)
{
    myname = name_;
    myid = _id;
    uname = name;
    id = id_;
    ui->setupUi(this);
    setWindowTitle(uname);

//    //设置背景
//    QPalette pal = this->palette();
//    pal.setBrush(QPalette::Background,QBrush(QPixmap("://p5.jpeg")));
//    setPalette(pal);

    connect(ui->close, &QPushButton::clicked, this, &Chat::close);
    //发送文件
    QThread *t = new QThread;
    worker = new SendFile;
    worker->moveToThread(t);
    t->start();
    connect(worker, &SendFile::sendFileContent, this, [=](int size, QString data){
        emit sendFileContent(myid, id, size, data);
    });
    connect(worker, &SendFile::over, this, [=](){
        QMessageBox::information(this, "文件传输", "文件发送完毕");
    });
}

Chat::~Chat()
{
    delete ui;
}

void Chat::recvMsg(QString msg)
{
    ui->chatText->append(uname+": "+msg);
}

void Chat::recvFileText(QString data_)
{
    if (flag == 0) {
        file = new QFile(data_);
        file->open(QIODevice::ReadWrite|QIODevice::Append);
        ui->chatText->append(uname+" send "+data_+" to you.");
    }
    if (flag != 0) file->write(data_.toUtf8());
    flag++;
    if (flag == 2) {
        file->close();
        flag = 0;
        QMessageBox::information(this, "文件传输", "文件接收完毕");
    }
}

void Chat::recvGroupMsg(QString from, QString msg)
{
    ui->chatText->append(from+": "+msg);
}

void Chat::on_send_clicked()
{
    QString content = ui->input->toPlainText();
    ui->input->clear();
    ui->chatText->append(myname+": "+content);
    qDebug() << "####" << id;
    emit sendId_Msg(myid, id, content);
}

void Chat::on_sendFile_clicked()
{
     QString path = QFileDialog::getOpenFileName();
     worker->sendFile(path);
}

void Chat::on_tiPeople_clicked()
{
    if (myid.size() > 5) {
        QString tp = ui->lineEdit->text();
        emit sendTp(tp);
    } else {
        QMessageBox::information(this, "提示", "没有权限");
    }
}

void Chat::on_noSay_clicked()
{
    if (myid.size() > 5) {
        QString noSay = ui->lineEdit_2->text();
        emit sendNoSay(noSay);
    } else {
        QMessageBox::information(this, "提示", "没有权限");
    }
}

void Chat::on_openSay_clicked()
{
    if (myid.size() > 5) {
        QString openSay = ui->lineEdit_3->text();
        emit sendOpenSay(openSay);
    } else {
        QMessageBox::information(this, "提示", "没有权限");
    }
}
